<?php
/**
 * @package		Joomla.Site
 * @subpackage	com_users
 * @copyright	Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

require_once JPATH_COMPONENT.'/controller.php';

/**
 * Profile controller class for Users.
 *
 * @package		Joomla.Site
 * @subpackage	com_users
 * @since		1.6
 */
class UsersControllerProfile extends UsersController
{
	/**
	 * Method to check out a user for editing and redirect to the edit form.
	 *
	 * @since	1.6
	 */
	public function edit()
	{
		$app			= JFactory::getApplication();
		$user			= JFactory::getUser();
		$loginUserId	= (int) $user->get('id');
		
		//[V] prepare edit
		$next="index.php?option=com_users&view=profile&layout=edit";
		$dat = JRequest::getVar('jform', array(), 'post', 'array');
		
		//1st page
		if(isset($dat["fornavn"])){
			$dat["name"]=$dat["fornavn"] ." ". $dat["efternavn"];
			$dat["Fornavn"]=$dat["fornavn"];
			$dat["Efternavn"]=$dat["efternavn"];
			unset($dat["fornavn"]);
			unset($dat["efternavn"]);
		}
		
		function checkfalse($var){
			if($var || $var==="0")
				return true;
		}
		
		if(isset($dat["weekdown"]))
			{$user->information=preg_replace("#weekdown:\d*?;#","weekdown:".$dat["weekdown"].";",$user->information);unset($dat["weekdown"]);}
		if(isset($dat["weightdown"]))
			{$user->information=preg_replace("#weightdown:\d*?;#","weightdown:".$dat["weightdown"].";",$user->information);unset($dat["weightdown"]);}
		if(isset($dat["civilstatus"]))
			{$user->information=preg_replace("#civilstatus:[^;]*?;#","civilstatus:".$dat["civilstatus"].";",$user->information);unset($dat["civilstatus"]);}
		if(isset($dat["kidage"]))
			{$user->information=preg_replace("#choicemaker:[^;]*?;#","choicemaker:".implode(',',array_filter($dat["kidage"],"checkfalse")).";",$user->information);unset($dat["choicemaker"]);unset($dat["kidage"]);}
		if(isset($dat["hvorkg"]))
			{$user->information=preg_replace("#hvorkg:[^;]*?;#","hvorkg:".implode(',',array_filter($dat["hvorkg"])).";",$user->information);unset($dat["hvorkg"]);}
		
		if(isset($dat["name"])){
			$next="index.php?option=com_users&view=profile&layout=edit2";
			foreach($dat as $k => $v)
				$user->$k=$v;
		}
		//end 1st page
		
		//2nd page
		if(isset($dat["breakfast"])){
			$user->information=preg_replace("#breakfast:[^;]*?;#","breakfast:".$dat["breakfast"] .";",$user->information);
		}
		if(isset($dat["soda"])){
			$user->information=preg_replace("#soda:[^;]*?;#","soda:".$dat["soda"] .";",$user->information);
		}
		if(isset($dat["eatwell"])){
			$user->information=preg_replace("#eatwell:[^;]*?;#","eatwell:".$dat["eatwell"] .";",$user->information);
		}
		if(isset($dat["roiloan"])){
			$user->information=preg_replace("#roiloan:[^;]*?;#","roiloan:".$dat["roiloan"] .";",$user->information);
		}
		if(isset($dat["meal1a"])){
			$tmp=$dat["meal1a"].'-'.$dat["meal1b"].
		';meal2:'.$dat["meal2a"].'-'.$dat["meal2b"].
		';meal3:'.$dat["meal3a"].'-'.$dat["meal3b"].
		';meal4:'.$dat["meal4a"].'-'.$dat["meal4b"].
		';meal5:'.$dat["meal5a"].'-'.$dat["meal5b"];
			$user->information=preg_replace("#meal1:.*?;diversity#","meal1:".$tmp.";diversity",$user->information);
		}
		if(isset($dat["diversity"])){
			$user->information=preg_replace("#diversity:[^;]*?;#","diversity:".$dat["diversity"] .";",$user->information);
		}
		if(isset($dat["cooktime"])){
			$user->information=preg_replace("#cooktime:[^;]*?;#","cooktime:".$dat["cooktime"] .";",$user->information);
		}
		if(isset($dat["fav"])){
			$dat["fav"]=implode(",",array_keys($dat["fav"]))."-".implode(',',$dat["fav"]);
			$user->information=preg_replace("#fav:[^;]*?;#","fav:".$dat["fav"] .";",$user->information);
			$next="index.php?option=com_users&view=profile&layout=edit3";
		}
		if(isset($dat["allergy"])){
			$user->information=preg_replace("#allergy:[^;]*?;#","allergy:".$dat["allergy"] .";",$user->information);
		}
		//end 2nd page
		
		//3rd page
		$dat = JRequest::get( 'post' );
		
		if(isset($dat["meget"])){
			$user->information=preg_replace("#meget:[^;]*?;#","meget:".$dat["meget"] .";",$user->information);
		}
		if(isset($dat["exercise"])){
			$dat["exercise"]=implode(",",array_keys($dat["exercise"]))."-".implode(',',$dat["exercise"]);
			$user->information=preg_replace("#exercise:[^;]*?;#","exercise:".$dat["exercise"] .";",$user->information);
		}
		if(isset($dat["omugen"])){
			$user->information=preg_replace("#omugen:[^;]*?;#","omugen:".$dat["omugen"] .";",$user->information);
		}
		if(isset($dat["workoutinweek"])){
			$dat["workoutinweek"]=implode(",",array_keys($dat["workoutinweek"]))."-".implode(',',$dat["workoutinweek"]);
			$user->information=preg_replace("#workoutinweek:[^;]*?;#","workoutinweek:".$dat["workoutinweek"] .";",$user->information);
		}
		if(isset($dat["hvormeget"])){
			$user->information=preg_replace("#hvormeget:[^;]*?;#","hvormeget:".$dat["hvormeget"] .";",$user->information);
		}
		if(isset($dat["motive"])){
			$user->information=preg_replace("#motive:[^;]*?;#","motive:".$dat["motive"] .";",$user->information);
			
			$model	= $this->getModel('Profile', 'UsersModel');
			$dat=array( "id" => $user->id,
			//"username" => $user->username,//for form
			"Fornavn" => $user->Fornavn,//for form
			"Efternavn" => $user->Efternavn,//for form
			"name" => $user->name,//for form
			"Alder" => $user->Alder,
			"Højde" => $user->Højde,
			"Vægt" => $user->Vægt,
			"skype" => $user->skype,
			"Mobiltelefon" => $user->Mobiltelefon,
			"email1" => $user->email,//for form
			"email2" => $user->email,//for form
			"information" => $user->information,
			);
			$form = $model->getForm();
			$data = $model->validate($form, $dat);
			if($data===false){
				$errors	= $model->getErrors();
				$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
			}
			$dat=$model->save($dat);
			if($dat===false)
				$this->setMessage(JText::sprintf('COM_USERS_PROFILE_SAVE_FAILED', $model->getError()), 'warning');
			else
				$this->setMessage(JText::_('COM_USERS_PROFILE_SAVE_SUCCESS'));
		}
		//end 3rd page
		
		// Get the previous user id (if any) and the current user id.
		$previousId = (int) $app->getUserState('com_users.edit.profile.id');
		$userId	= (int) JRequest::getInt('user_id', null, '', 'array');

		// Check if the user is trying to edit another users profile.
		if ($userId != $loginUserId) {
			JError::raiseError(403, JText::_('JERROR_ALERTNOAUTHOR'));
			return false;
		}

		// Set the user id for the user to edit in the session.
		$app->setUserState('com_users.edit.profile.id', $userId);

		// Get the model.
		$model = $this->getModel('Profile', 'UsersModel');

		// Check out the user.
		if ($userId) {
			$model->checkout($userId);
		}

		// Check in the previous user.
		if ($previousId) {
			$model->checkin($previousId);
		}

		// Redirect to the edit screen.
		$this->setRedirect($next);//JRoute::_('index.php?option=com_users&view=profile&layout=edit', false));
	}

	/**
	 * Method to save a user's profile data.
	 *
	 * @return	void
	 * @since	1.6
	 */
	public function save()
	{
		// Check for request forgeries.
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Initialise variables.
		$app	= JFactory::getApplication();
		$model	= $this->getModel('Profile', 'UsersModel');
		$user	= JFactory::getUser();
		$userId	= (int) $user->get('id');

		// Get the user data.
		$data = JRequest::getVar('jform', array(), 'post', 'array');

		// Force the ID to this user.
		$data['id'] = $userId;

		// Validate the posted data.
		$form = $model->getForm();
		if (!$form) {
			JError::raiseError(500, $model->getError());
			return false;
		}

		// Validate the posted data.
		$data = $model->validate($form, $data);

		// Check for errors.
		if ($data === false) {
			// Get the validation messages.
			$errors	= $model->getErrors();

			// Push up to three validation messages out to the user.
			for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
				if ($errors[$i] instanceof Exception) {
					$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
				} else {
					$app->enqueueMessage($errors[$i], 'warning');
				}
			}

			// Save the data in the session.
			$app->setUserState('com_users.edit.profile.data', $data);

			// Redirect back to the edit screen.
			$userId = (int) $app->getUserState('com_users.edit.profile.id');
			$this->setRedirect(JRoute::_('index.php?option=com_users&view=profile&layout=edit&user_id='.$userId, false));
			return false;
		}

		// Attempt to save the data.
		$return	= $model->save($data);

		// Check for errors.
		if ($return === false) {
			// Save the data in the session.
			$app->setUserState('com_users.edit.profile.data', $data);

			// Redirect back to the edit screen.
			$userId = (int)$app->getUserState('com_users.edit.profile.id');
			$this->setMessage(JText::sprintf('COM_USERS_PROFILE_SAVE_FAILED', $model->getError()), 'warning');
			$this->setRedirect(JRoute::_('index.php?option=com_users&view=profile&layout=edit&user_id='.$userId, false));
			return false;
		}

		// Redirect the user and adjust session state based on the chosen task.
		switch ($this->getTask()) {
			case 'apply':
				// Check out the profile.
				$app->setUserState('com_users.edit.profile.id', $return);
				$model->checkout($return);

				// Redirect back to the edit screen.
				$this->setMessage(JText::_('COM_USERS_PROFILE_SAVE_SUCCESS'));
				$this->setRedirect(JRoute::_(($redirect = $app->getUserState('com_users.edit.profile.redirect')) ? $redirect : 'index.php?option=com_users&view=profile&layout=edit&hidemainmenu=1', false));
				break;

			default:
				// Check in the profile.
				$userId = (int)$app->getUserState('com_users.edit.profile.id');
				if ($userId) {
					$model->checkin($userId);
				}

				// Clear the profile id from the session.
				$app->setUserState('com_users.edit.profile.id', null);

				// Redirect to the list screen.
				$this->setMessage(JText::_('COM_USERS_PROFILE_SAVE_SUCCESS'));
				$this->setRedirect(JRoute::_(($redirect = $app->getUserState('com_users.edit.profile.redirect')) ? $redirect : 'index.php?option=com_users&view=profile&user_id='.$return, false));
				break;
		}

		// Flush the data from the session.
		$app->setUserState('com_users.edit.profile.data', null);
	}
}